package cn.bdqn.controller;


import cn.bdqn.utils.Json;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static cn.bdqn.utils.RedisConstants.LOGIN_CODE_KEY;
import static cn.bdqn.utils.RedisConstants.LOGIN_CODE_TTL;


@RestController
@RequestMapping("/api")
public class CaptchaController {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${captcha.type}")
    private String type;

    @GetMapping("/verification")
    public HashMap<String, Object> verification(HttpServletResponse response) throws IOException {
        HashMap<String, Object> ok = new HashMap<>();
        String token = null;
        FastByteArrayOutputStream os = null;
        String capStr = null;
        String code = null;
        BufferedImage image = null;
        try {
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
//            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            if ("math".equals(type)){
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);
            }
            else if ("char".equals(type)) {
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
            }
            //随机token

            token = IdUtil.nanoId(5);
            redisTemplate.opsForValue().set(LOGIN_CODE_KEY+token,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
            os = new FastByteArrayOutputStream();
            ImageIO.write(image, "jpg", os);
            os.flush();
        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (os != null) {
                os.close();
            }
        }
        ok.put("uuid",token);
        ok.put("img", Base64.encode(os.toByteArray()));
        return ok;
    }
    @GetMapping("/AuthenticationToken/{uuid}/{usercode}")
    public Json AuthenticationToken(@PathVariable("uuid") String uuid, @PathVariable("usercode") String usercode){
        ValueOperations valueOperations=redisTemplate.opsForValue();
        Object o = valueOperations.get(LOGIN_CODE_KEY+uuid);
        Json json=null;
        if(o.toString().equals(usercode)){
            json=new Json();
            json.setCode(200);
        }else{
            json=new Json();
            json.setCode(400);
        }
        return json;
    }
}